import os
import gradio as gr
from openai import OpenAI
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Initialize OpenAI client
client = OpenAI(
    api_key=os.getenv("LLM_API_KEY"),
    base_url=os.getenv("LLM_BASE_URL"),
)

def explain_code(code, language, detail_level):
    levels = {
        "简单": "用简单易懂的方式为初学者解释这段{language}代码。",
        "详细": "详细解释这段{language}代码，包括技术细节和最佳实践。",
        "高级": "从专家角度分析这段{language}代码，包括性能考虑和潜在优化。"
    }

    prompt_template = levels.get(detail_level, levels["简单"])
    prompt = f"{prompt_template} Code: {code}"

    try:
        response = client.chat.completions.create(
            model=os.getenv("LLM_MODEL"),
            messages=[{"role": "user", "content": prompt}],
            max_tokens=600,
            temperature=0.3
        )
        explanation = response.choices[0].message.content.strip()
        return explanation
    except Exception as e:
        return f"抱歉，解释过程中出现错误。请检查网络连接和API配置。\n技术详情: {str(e)}"

# Gradio interface
with gr.Blocks(title="AI 代码解释器", theme=gr.themes.Soft()) as iface:
    gr.Markdown("# 🤖 AI 代码解释器\n输入代码，获取AI驱动的详细解释和改进建议")

    with gr.Row():
        with gr.Column(scale=1):
            code_input = gr.Code(
                label="🔧 代码输入",
                language="python",
                lines=10
            )

            language_input = gr.Dropdown(
                label="💻 编程语言",
                choices=["Python", "JavaScript", "Java", "C++", "C#", "Go", "Rust", "TypeScript", "PHP", "Ruby", "Swift", "Kotlin", "Dart", "其他 (Other)"],
                value="Python",
                info="选择代码的编程语言以获得更准确的解释"
            )

            detail_level = gr.Radio(
                label="📚 解释详细程度",
                choices=["简单", "详细", "高级"],
                value="详细",
                info="简单：适合初学者；详细：包含技术细节；高级：从专家角度分析"
            )

        with gr.Column(scale=1):
            output = gr.Textbox(
                label="💡 AI 解释结果",
                lines=12,
                placeholder="解释结果将在这里显示...",
                show_copy_button=True
            )

    submit_btn = gr.Button("🚀 开始解释", variant="primary", size="lg")
    clear_btn = gr.Button("🗑️ 清除内容", variant="secondary")

    submit_btn.click(
        fn=explain_code,
        inputs=[code_input, language_input, detail_level],
        outputs=output
    )

    clear_btn.click(
        fn=lambda: ("", "Python", "详细", ""),
        inputs=[],
        outputs=[code_input, language_input, detail_level, output]
    )

if __name__ == "__main__":
    iface.launch()
